package com.hxd.otc.module.home.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.mvp.base.BasePresenter;
import com.hxd.otc.utils.GsonUtil;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.utils.hyphenate.ListenerManager;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.callback.ValueCallBack;
import com.hyphenate.helpdesk.domain.NewTicketBody;
import com.hyphenate.helpdesk.easeui.widget.AlertDialogFragment;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 发起留言界面
 */
public class NewLeaveMessageActivity extends BaseActivity {



    private ProgressDialog progressDialog;

    @BindView(R.id.rl_new_leave_success)
    RelativeLayout successLayout;
    @BindView(R.id.et_new_leave_content)
    EditText contentText;
    @BindView(R.id.et_name)
    EditText itemName;
    @BindView(R.id.et_phone)
    EditText itemPhone;
    @BindView(R.id.et_email)
    EditText itemEmail;
    @BindView(R.id.et_theme)
    EditText itemTheme;
    @BindView(R.id.rl_detail_content)
    RelativeLayout detailLayout;
    @BindView(R.id.tv_detail)
    TextView detailText;
    @BindView(R.id.tv_send)
    TextView tvSend;

    @Override
    protected int getLayoutId() {
        return R.layout.em_activity_newleave;
    }

    protected void initView() {
        contentText.requestFocus();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        //输入法回车焦点切换
        itemName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    itemPhone.requestFocus();
                    return true;
                }
                return false;
            }
        });
        itemPhone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    itemEmail.requestFocus();
                    return true;
                }
                return false;
            }
        });
        itemEmail.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    itemTheme.requestFocus();
                    return true;
                }
                return false;
            }
        });
        itemTheme.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    assert imm != null;
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    itemTheme.clearFocus();
                    return true;
                }
                return false;
            }
        });

    }


    @OnClick({R.id.tv_send, R.id.rl_name, R.id.rl_phone, R.id.rl_email, R.id.rl_theme})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_name:
                itemName.requestFocus();
                break;
            case R.id.rl_phone:
                itemPhone.requestFocus();
                break;
            case R.id.rl_email:
                itemEmail.requestFocus();
                break;
            case R.id.rl_theme:
                itemTheme.requestFocus();
                break;
            case R.id.tv_send:
                if (hasItemsNoValue()) {
                    showToast(getString(R.string.new_leave_item_empty_value_toast));
                    return;
                }
                contentText.requestFocus();
                commitLeaveMessage();
                break;
        }
    }

    private boolean hasItemsNoValue() {
        return itemName.getText().toString().length() == 0
                || itemPhone.getText().toString().length() == 0
                || itemEmail.getText().toString().length() == 0
                || itemTheme.getText().toString().length() == 0;
    }

    private void commitLeaveMessage() {
        if (!ChatClient.getInstance().isLoggedInBefore()) {
            // 未成功登录不允许发送留言信息
            return;
        }

        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(getString(R.string.leave_sending));
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();


        NewTicketBody ticketBody = new NewTicketBody();
        ticketBody.setContent(contentText.getText().toString());
        ticketBody.setSubject(itemTheme.getText().toString());
        NewTicketBody.CreatorBean creatorBean = new NewTicketBody.CreatorBean();
        creatorBean.setEmail(itemEmail.getText().toString());
        creatorBean.setName(itemName.getText().toString());
        creatorBean.setPhone(itemPhone.getText().toString());
        ticketBody.setCreator(creatorBean);

        String target = Constant.HyphenateKeFu.DEFAULT_CUSTOMER_ACCOUNT;
        String tenantId = Constant.HyphenateKeFu.DEFAULT_TENANT_ID;
        String projectId = Constant.HyphenateKeFu.DEFAULT_PROJECT_ID;
        ChatClient.getInstance().leaveMsgManager().createLeaveMsg(GsonUtil.toJson(ticketBody), projectId, target, new ValueCallBack<String>() {

            @Override
            public void onSuccess(final String value) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UIUtils.dismissDialog(progressDialog);
                        ListenerManager.getInstance().sendBroadCast("NewTicketEvent", null);
                        LogUtils.d("value:" + value);
                        tvSend.setVisibility(View.GONE);
                        contentText.setVisibility(View.GONE);
                        successLayout.setVisibility(View.VISIBLE);
                        itemName.setKeyListener(null);
                        itemPhone.setKeyListener(null);
                        itemEmail.setKeyListener(null);
                        itemTheme.setKeyListener(null);
                        detailLayout.setVisibility(View.VISIBLE);
                        detailText.setText(contentText.getText().toString());
                    }
                });
            }

            @Override
            public void onError(int code, final String error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UIUtils.dismissDialog(progressDialog);
                        LogUtils.e("error:" + error);
                        if (!NewLeaveMessageActivity.this.isFinishing()) {
                            showAlertDialog();
                        }
                    }
                });
            }

        });
    }

    private void showAlertDialog() {
        FragmentTransaction mFragTransaction = getSupportFragmentManager().beginTransaction();
        String fragmentTag = "dialogFragment";
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(fragmentTag);
        if (fragment != null) {
            //为了不重复显示dialog，在显示对话框之前移除正在显示的对话框
            mFragTransaction.remove(fragment);
        }
        final AlertDialogFragment dialogFragment = new AlertDialogFragment();
        dialogFragment.setTitleText(getString(R.string.new_leave_msg_sub_fail));
        dialogFragment.setContentText(getString(R.string.new_leave_msg_sub_fail_alert_content));
        dialogFragment.setRightBtnText(getString(R.string.new_leave_msg_alert_ok));
        dialogFragment.show(mFragTransaction, fragmentTag);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(progressDialog);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

}
